function fv = fvfix(rate, nper, p, pv, due)
%FVFIX  Future value with fixed periodic payments.
%
%   FV = fvfix(RATE, NPER, P)
%   FV = fvfix(RATE, NPER, P, PV, DUE)
%
%   Optional parameters: PV, DUE
%
%   Inputs:
%   RATE - Scalar or vector of periodic interest rates.
%
%   NPER - Scalar or vector of the number of periods.
%
%      P - Scalar or vector of periodic payments.
%
%   Optional inputs:
%     PV - Scalar or vector of the initial value. Default PV = 0.
%
%    DUE - Scalar or vector of 0's or 1's that specify whether payments
%          are made at the beginning of a period (DUE = 1) or whether payments
%          are made at the end of a period (DUE = 0).  Default DUE = 0.
%
%   Outputs:
%      FV - Scalar or vector of future values.
%
%   Example:
%      A savings account has a starting balance of $1500. $200 is added at the
%      end of each month for 10 years and the account pays 9% interest
%      compounded monthly.
%
%      fv = fvfix(.09/12, 12*10, 200, 1500, 0)
%      fv = 42379.89
%
%   See also PVFIX, PVVAR, FVVAR.
 
%       Copyright 1995-2006 The MathWorks, Inc.
%       $Revision: 1.6.2.7 $   $Date: 2006/06/16 20:09:46 $ 

%---------------------------------------------
% Input validation
%---------------------------------------------
if nargin < 3
    error('Finance:fvfix:notEnoughInputs', 'Too few inputs.')
end

if nargin < 4
    pv = zeros(size(p)); % Default present initial value is 0.
end

if nargin < 5
    due = zeros(size(p)); % Payments made at end of period
end

if any(any(due ~= 0 & due ~= 1))
    error('Finance:fvfix:invalidDue', 'DUE must be 0 or 1.')
end

if isempty(rate) || isempty(nper) || isempty(p) || isempty(pv) || isempty(due)
    fv = [];
    return
end

%scalar expansion
[rate,nper,p,pv,due] = finargsz('scalar', rate,nper,p,pv,due); 

fv = zeros(size(p));

    % Algorithm
    c = 1+rate;

    i = find(due == 0);
    if ~isempty(i)
        hold = pv.*c.^nper+p.*(1-c.^nper)./(1-c);
        fv(i) = hold(1:numel(i));
    end

    j = find(due == 1);
    if ~isempty(j)
        hold2 = (pv+p).*c.^nper+p.*(1-c.^nper)./(1-c)-p;
        fv(j) = hold2(1:numel(j));
    end



% [EOF]
